/*
 * Copyright (C) 2016+ AzerothCore <www.azerothcore.org>, released under GNU AGPL v3 license: https://github.com/azerothcore/azerothcore-wotlk/blob/master/LICENSE-AGPL3
 */
#include "PlayerLevelUpGiftScript.h"
#include "Chat.h"
#include "Common.h"
#include "Config.h"
#include "Player.h"
#include "PlayerGift.h"
#include "ScriptMgr.h"
#include <fstream>


 std::vector<string> KKK_CHAT_MSG_IGNORE_KEYS =
    {
        "Absorbs_UnitStats",
        "ATR",
        "BF_VERSION_WITH_CHECK",
        "CAIO",
        "DBMv4",
        "DTLS",
        "ELVUI_VERSIONCHK",
        "ElvUIPluginVC",
        "GS_ToolTips_Request",
        "GTFO_v",
        "LFG",
        "LHC40",
        "LFW",
        "LibGroupTalents",
        "LOOT_OPENED",
        "oRA3",
        "PLPWR",
        "Quixote2",
        "RAIDTOTEMS",
        "RAL_SELECT",
        "RECOUNT",
        "RAL_SELECTREPLY",
        "RAL_SELECT",
        "SpecializedAbsorbs_",
        "BLT Glyphs",
        "PS-myvers"
        
    };


PlayerLevelUpGiftScript *playerLevelUpGiftScript;

PlayerLevelUpGiftScript::PlayerLevelUpGiftScript() : PlayerScript("PlayerLevelUpGiftScript"), WorldScript("PlayerLevelUpGiftScript")
{
    //setReloadRequiredFlag();
}

void PlayerLevelUpGiftScript::OnStartup()
{
    init();
}

/**
 * Acturlly this method should be in another CPP file. LOL
*/
void PlayerLevelUpGiftScript::OnPlayerGiveXP(Player* player, uint32& amount, Unit* victim, uint8 xpSource) 
{
    if (sConfigMgr->GetOption<bool>(KKK_MODULE_ENABLE_KEY, false)) {
        uint32 xpRateValue = this->xpRate.getXpRate(player);
        uint32 amountTemp = amount;
        amountTemp *= xpRateValue;
        amountTemp /= 100;
        if( amountTemp > 0){
            amount = amountTemp;
        }
    }
   
}

void PlayerLevelUpGiftScript::OnPlayerLevelChanged(Player *player, uint8 oldlevel)
{
    if (sConfigMgr->GetOption<bool>(KKK_MODULE_ENABLE_KEY, false)) {
        static string _sys_msg_prefix = ">>>升级礼包<<< 请注意查收礼包邮件：";
        uint8 currentLevel = player->GetLevel();
        LevelUpGift *gift = playerGiftCenter.getGiftByeLevel(currentLevel);
        if (gift != nullptr) {
            gift->mailTo(player);
            ChatHandler(player->GetSession()).SendSysMessage(_sys_msg_prefix + gift->getBody());
        }
    }
}

void PlayerLevelUpGiftScript::OnPlayerUpdateCraftingSkill(Player* player, SkillLineAbilityEntry const* skill, uint32 current_level, uint32& gain)
{   
    //ChatHandler(player->GetSession()).PSendSysMessage("附魔 %s skillline:%d cur:%d gain:%d",player->GetName(),skill->SkillLine,current_level,gain);
    if (sConfigMgr->GetOption<bool>(KKK_MODULE_ENABLE_KEY, false)) {
        uint32 currentLevel =current_level + gain;
        if( skill->SkillLine == SKILL_LINE_ENCHANTING && gain > 0){
            static string _sys_msg_prefix = ">>>附魔礼包<<< 请注意查收礼包邮件：";
           
            LevelUpGift *gift = playerGiftCenter.getGiftByEnchantingLevel(currentLevel);
            if (gift != nullptr) {
                gift->mailTo(player);
                ChatHandler(player->GetSession()).SendSysMessage(_sys_msg_prefix + gift->getBody());
            }
        }
    }
}

bool PlayerLevelUpGiftScript::shouldLog(std::string msg)
{
    bool shouldLog = true;
    for(std::string ignoreKey : KKK_CHAT_MSG_IGNORE_KEYS){
        if(msg.find(ignoreKey) != std::string::npos){
            shouldLog = false;
            break;
        } 
    }
    return shouldLog;
}
void PlayerLevelUpGiftScript::init()
{
    if (sConfigMgr->GetOption<bool>(KKK_MODULE_ENABLE_KEY, false)) {
        LOG_INFO("kkk gift module.init", ">> Init start");
        playerGiftCenter.init();
        this->xpRate.init();
        LOG_INFO("kkk gift module.init", ">> Init done");

        this->logChat("kkk","server","server start");
    }
}

void PlayerLevelUpGiftScript::logChat(std::string sender /* not null */,
                                        std::string recver /* not null; player name,guild name etc */, 
                                        std::string msg /* not null*/){
    if (sConfigMgr->GetOption<bool>(KKK_MODULE_ENABLE_KEY, false)) {
        static std::string const &key = KKK_MODULE_CHAT_LOG_PATH_KEY;
        static std::string const &def= "";
        //std::string logFilePath = sConfigMgr->GetStringDefault(KKK_MODULE_CHAT_LOG_PATH_KEY, "",false);
        std::string logFilePath = sConfigMgr->GetOption(key,def);
        if(logFilePath == ""){
            return;
        }
        if( !this->shouldLog(msg) ){
            return;
        }
        time_t now = time(nullptr);
        char timebuf[32];
        strftime(timebuf,sizeof(timebuf),"%Y-%m-%d",localtime(&now));
        std::string filenameDate = timebuf;

        strftime(timebuf,sizeof(timebuf),"%Y-%m-%d %H:%M:%S",localtime(&now));
   

        std::ofstream file;
        file.open(logFilePath + "/" + KKK_MODULE_CHAT_LOG_PREFIX + filenameDate + ".log",std::ios_base::app);

        if( !file.good()){
            return;
        }

        file << "[" << timebuf << "]" << sender << ">" << recver << ": " << msg << std::endl;
        file.flush();
        file.close();

    }                                         
}

vector<LevelUpGift *> PlayerLevelUpGiftScript::getGifts()
{
    return playerGiftCenter.getAllGift();
}


// Add all scripts in one
void levelupGiftScripts()
{
    playerLevelUpGiftScript = new PlayerLevelUpGiftScript();
}
